package com.weiter.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weiter.common.core.constant.CacheConstants;
import com.weiter.common.core.constant.UserConstants;
import com.weiter.common.core.core.domain.entity.SysDictData;
import com.weiter.common.core.core.page.PageQuery;
import com.weiter.common.core.service.SysDictApiService;
import com.weiter.common.core.utils.StringUtils;
import com.weiter.common.core.utils.spring.SpringUtils;
import com.weiter.common.redis.service.RedisService;
import com.weiter.system.mapper.SysDictDataMapper;
import com.weiter.system.service.ISysDictDataService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 字典数据
 * @author weiter
 */
@Service
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictData> implements ISysDictDataService, SysDictApiService {

    @Resource
    private SysDictDataMapper dictDataMapper;

    /**
     * 分隔符
     */
    public static final String SEPARATOR = ",";

    /**
     * 查询字典数据分页列表
     * @param query     字典数据查询条件
     * @param pageQuery 分页查询信息
     * @return 字典数据分页列表
     */
    @Override
    public Page<SysDictData> selectDictDataPage(SysDictData query, PageQuery pageQuery) {
        LambdaQueryWrapper<SysDictData> lqw = buildQueryWrapper(query);
        return dictDataMapper.selectPage(pageQuery.build(), lqw);
    }

    /**
     * 查询数据类型列表
     * @param query 字典数据查询条件
     * @return 字典数据列表
     */
    @Override
    public List<SysDictData> selectDictDataList(SysDictData query) {
        LambdaQueryWrapper<SysDictData> lqw = buildQueryWrapper(query);
        return dictDataMapper.selectList(lqw);
    }

    /**
     * 查询字典数据
     * @param dictType 字典类型
     * @return 字典数据集合
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType) {
        return dictDataMapper.selectList(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getDictType, dictType)
                .eq(SysDictData::getStatus, UserConstants.DICT_NORMAL).orderByAsc(SysDictData::getDictSort));
    }

    /**
     * 新增字典数据
     * @param data 字典数据
     * @return 结果
     */
    @Override
    public int insertDictData(SysDictData data) {
        int row = dictDataMapper.insert(data);
        if (row > 0) {
            List<SysDictData> dictDataList = this.selectDictDataByType(data.getDictType());
            this.setDictCache(data.getDictType(), dictDataList);
        }
        return row;
    }

    /**
     * 修改字典数据
     * @param data 字典数据
     * @return 结果
     */
    @Override
    public int updateDictData(SysDictData data) {
        int row = dictDataMapper.updateById(data);
        if (row > 0) {
            List<SysDictData> dictDataList = this.selectDictDataByType(data.getDictType());
            this.setDictCache(data.getDictType(), dictDataList);
        }
        return row;
    }

    /**
     * 删除字典数据
     * @param dictCodes 需要删除的字典数据ID
     */
    @Override
    public void deleteDictDataByIds(Long[] dictCodes) {
        for (Long dictCode : dictCodes) {
            SysDictData data = dictDataMapper.selectById(dictCode);
            dictDataMapper.deleteById(dictCode);
            // 更新缓存
            List<SysDictData> dictDataList = this.selectDictDataByType(data.getDictType());
            this.setDictCache(data.getDictType(), dictDataList);
        }
    }

    /**
     * 设置字典缓存
     * @param key       参数键
     * @param dictDatas 字典数据列表
     */
    @Override
    public void setDictCache(String key, List<SysDictData> dictDatas) {
        SpringUtils.getBean(RedisService.class).setCacheObject(CacheConstants.SYS_DICT_KEY + key, dictDatas);
    }

    /**
     * 获取字典缓存
     * @param key 参数键
     * @return dictDatas 字典数据列表
     */
    @Override
    public List<SysDictData> getDictCache(String key) {
        JSONArray arrayCache = SpringUtils.getBean(RedisService.class).getCacheObject(CacheConstants.SYS_DICT_KEY + key);
        if (StringUtils.isNotNull(arrayCache)) {
            return arrayCache.toList(SysDictData.class);
        }
        return null;
    }

    /**
     * 根据字典类型和字典值获取字典标签
     * @param dictType  字典类型
     * @param dictValue 字典值
     * @return 字典标签
     */
    @Override
    public String getDictLabelForApi(String dictType, String dictValue) {
        if (StringUtils.isEmpty(dictValue)) {
            return StringUtils.EMPTY;
        }
        return getDictLabelForApi(dictType, dictValue, SEPARATOR);
    }

    /**
     * 根据字典类型和字典标签获取字典值
     * @param dictType  字典类型
     * @param dictLabel 字典标签
     * @return 字典值
     */
    @Override
    public String getDictValueForApi(String dictType, String dictLabel) {
        if (StringUtils.isEmpty(dictLabel)) {
            return StringUtils.EMPTY;
        }
        return getDictValueForApi(dictType, dictLabel, SEPARATOR);
    }

    /**
     * 根据字典类型和字典值获取字典标签
     * @param dictType  字典类型
     * @param dictValue 字典值
     * @param separator 分隔符
     * @return 字典标签
     */
    @Override
    public String getDictLabelForApi(String dictType, String dictValue, String separator) {
        StringBuilder propertyString = new StringBuilder();
        List<SysDictData> datas = this.getDictCache(dictType);
        if (StringUtils.isNull(datas)) {
            return StringUtils.EMPTY;
        }
        if (StringUtils.containsAny(separator, dictValue)) {
            for (SysDictData dict : datas) {
                for (String value : dictValue.split(separator)) {
                    if (value.equals(dict.getDictValue())) {
                        propertyString.append(dict.getDictLabel()).append(separator);
                        break;
                    }
                }
            }
        } else {
            for (SysDictData dict : datas) {
                if (dictValue.equals(dict.getDictValue())) {
                    return dict.getDictLabel();
                }
            }
        }
        return StringUtils.stripEnd(propertyString.toString(), separator);
    }

    /**
     * 根据字典类型和字典标签获取字典值
     * @param dictType  字典类型
     * @param dictLabel 字典标签
     * @param separator 分隔符
     * @return 字典值
     */
    @Override
    public String getDictValueForApi(String dictType, String dictLabel, String separator) {
        StringBuilder propertyString = new StringBuilder();
        List<SysDictData> datas = getDictCache(dictType);
        if (StringUtils.isNull(datas)) {
            return StringUtils.EMPTY;
        }
        if (StringUtils.containsAny(separator, dictLabel)) {
            for (SysDictData dict : datas) {
                for (String label : dictLabel.split(separator)) {
                    if (label.equals(dict.getDictLabel())) {
                        propertyString.append(dict.getDictValue()).append(separator);
                        break;
                    }
                }
            }
        } else {
            for (SysDictData dict : datas) {
                if (dictLabel.equals(dict.getDictLabel())) {
                    return dict.getDictValue();
                }
            }
        }
        return StringUtils.stripEnd(propertyString.toString(), separator);
    }

    /**
     * 根据字典类型获取字典所有值
     * @param dictType 字典类型
     * @return 字典值
     */
    @Override
    public String getDictValuesForApi(String dictType) {
        StringBuilder propertyString = new StringBuilder();
        List<SysDictData> datas = getDictCache(dictType);
        if (StringUtils.isNull(datas)) {
            return StringUtils.EMPTY;
        }
        for (SysDictData dict : datas) {
            propertyString.append(dict.getDictValue()).append(SEPARATOR);
        }
        return StringUtils.stripEnd(propertyString.toString(), SEPARATOR);
    }

    /**
     * 根据字典类型获取字典所有标签
     * @param dictType 字典类型
     * @return 字典值
     */
    @Override
    public String getDictLabelsForApi(String dictType) {
        StringBuilder propertyString = new StringBuilder();
        List<SysDictData> datas = getDictCache(dictType);
        if (StringUtils.isNull(datas)) {
            return StringUtils.EMPTY;
        }
        for (SysDictData dict : datas) {
            propertyString.append(dict.getDictLabel()).append(SEPARATOR);
        }
        return StringUtils.stripEnd(propertyString.toString(), SEPARATOR);
    }

    private LambdaQueryWrapper<SysDictData> buildQueryWrapper(SysDictData query) {
        LambdaQueryWrapper<SysDictData> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(query.getDictLabel()), SysDictData::getDictLabel, query.getDictLabel());
        lqw.like(StrUtil.isNotBlank(query.getDictType()), SysDictData::getDictType, query.getDictType());
        lqw.like(StrUtil.isNotBlank(query.getStatus()), SysDictData::getStatus, query.getStatus());
        lqw.orderByAsc(SysDictData::getDictSort);
        return lqw;
    }
}
